var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    mode: 'income',
    numList: [{
      name: '车辆要求'
    }, {
      name: '计价规则'
    }, {
      name: '价格模式'
    }, {
      name: '生效时间'
    }],
    num: -1,
    curNum:0,
    vehicleLength:[],
    vehicleLengthIndex: -1,
    vehicleFunction: [],
    vehicleFunctionIndex: -1,
    vehicleSource: [],
    vehicleSourceIndex: -1,
    priceConfig:{},
    formula:'',
    startRegion: [],
    endRegion: [],
    startCity: false,
    endCity: false,
    start_date: moment().format('YYYY-MM-DD'),
    end_date: moment().format('YYYY-MM-DD'),
    start_time: '00:00',
    end_time: '23:59',
    auction_time_start: '00:00',
    auction_time_end: '23:59',
    guideStep:0, //向导步骤
    guideFormulaItem: [{ name: 'gf0', symbol1: 0, symbol2: 0,check:false}],
    symbolName: ['大于', '大于等于', '小于', '小于等于','等于'],
    symbolCode: ['>', '>=', '<', '<=', '='],
    symbolIndex:0,
    guideFormula:'',
    type: 'warehouse',
    priceType: 'formula',
    priceTypeList: [
      { name: '公式计价', type: "formula", value: '0', checked: true },
      { name: '区域计价', type: "region", value: '1' },
      { name: '收货点计价', type: "shop", value: '2' },
      { name: '收货点客户计价', type: "shop_customer", value: '3' }
    ],
    priceMode:0,
    priceModeSwitch:true,
    price_priority_mode:['竞价时间顺序','人工选择'],
    price_priority_mode_index:0,
    formType: 'add',
    lpp:false,
    auction_price_min_protect:0,
    dv_deadline:30,
    vehicle_tags_list: [],
    deputy_driver:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    if(e.id){
      this.setData({
        id:e.id
      })
    }
    if (e.type) {
      this.setData({
        type: e.type
      })
    }
    this.loadVehicleProperty();
  },
  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  priceTypeChange: function (e) {
    console.log(e.detail.value);

    var priceTypeList = this.data.priceTypeList, values = e.detail.value;
    var priceType = 'formula';
    for (var i = 0, lenI = priceTypeList.length; i < lenI; ++i) {
      priceTypeList[i].checked = false;

      for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (priceTypeList[i].value == values[j]) {
          priceTypeList[i].checked = true;
          priceType = priceTypeList[i].type;
          break;
        }
      }
    }

    this.setData({
      priceTypeList: priceTypeList,
      priceType: priceType
    });
  },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);

    if (this.data.startCity && that.data.startRegion.length == 3) {
      var startRegion = that.data.startRegion;
      startRegion.pop();
      this.setData({
        startRegion: startRegion
      })
    }
    if (this.data.endCity && that.data.endRegion.length == 3) {
      var endRegion = that.data.endRegion;
      endRegion.pop();
      this.setData({
        endRegion: endRegion
      })
    }
    if (item == 'priceModeSwitch'){
      that.setData({
        priceMode: e.detail.value == true?0:1
      })
    }
    if (item == 'lpp') {
      that.setData({
        auction_price_min_protect: e.detail.value == true ? 1 : 0
      })
    }
  },
  selectCompany: function () {
    wx.navigateTo({
      url: '/pages/carrier/selectCarrier'
    })
  }, 
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;

    var inputtype = e.currentTarget.dataset.inputtype;
    if (inputtype == 'digit' || inputtype == 'number') {
      if (isNaN(value)) {
        value = '';
      }
    }
    item_value[item] = value;
    that.setData(item_value);
  },
  bindStartRegionChange(e) {
    console.log(e.detail.value)
    if (this.data.startCity){
      var value = e.detail.value;
      value.pop();
      this.setData({
        startRegion: value
      })
    } else {
      this.setData({
        startRegion: e.detail.value
      })
    }
  },
  bindEndRegionChange(e) {
    if (this.data.endCity) {
      var value = e.detail.value;
      value.pop();
      this.setData({
        endRegion: value
      })
    } else {
      this.setData({
        endRegion: e.detail.value
      })
    }
  },
  formulaTextAreaBlur:function(e){
     this.setData({
       formula:e.detail.value
     })
  },
  search: function () {
    this.loadData();
  },
  //切换收入或支出
  changeMode:function(e){
     this.setData({
       mode:e.currentTarget.dataset.mode
     })
    this.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '获取数据...',
      mask: true
    })
    util.getData("/atapi/price/price/priceConfig", {
      'type':that.data.type,
      'customer': (that.data.type == 'customer'?that.data.id:''),
      'warehouse': (that.data.type == 'warehouse' ? that.data.id : ''),
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize,
      'mode': that.data.mode,
      'CO_ID': app.globalData.CO_ID
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        var _data = res.data.data[0];
        for(var i=0;i<_data.length;i++){
          var vehicleLengthIndex = that.data.vehicleLengthCode.indexOf(String(_data[i].vehicleLength))
          _data[i].vehicleLengthText = that.data.vehicleLength[vehicleLengthIndex];

          var vehicleSourceIndex = that.data.vehicleSourceCode.indexOf(String(_data[i].vehicleSource))
          _data[i].vehicleSourceText = that.data.vehicleSource[vehicleSourceIndex];
          
          var vehicleFunctionIndex = that.data.vehicleFunctionCode.indexOf(String(_data[i].vehicleFunction))
          _data[i].vehicleFunctionText = that.data.vehicleFunction[vehicleFunctionIndex];
        }
        that.setData({
          dataList: _data,
          count: count,
          pageNumber: pageNumber
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: []
        });
      }
      wx.hideLoading()
    });
  },
  editPrice: function (e) {
    var that = this;
    that.setData({
      num: -1,
      curNum: 0
    })
    var id = e.currentTarget.dataset.id;
    var dataList = that.data.dataList;
    var currentItem = {};
    for (var i = 0; i < dataList.length; i++) {
      if (dataList[i].ID == id) {
        currentItem = dataList[i];
        break;
      }
    }
    var priceType = currentItem.type, priceTypeList = that.data.priceTypeList;
    for (var i = 0; i < priceTypeList.length; i++) {
      if (priceTypeList[i].type == priceType) {
        priceTypeList[i].checked = true;
      } else {
        priceTypeList[i].checked = false;
      }
    }

    that.setData({
      pid: id,
      formula: currentItem.formula,
      R: currentItem.type == 'region' ? currentItem.formula:'',
      start_date: currentItem.start_date,
      end_date: currentItem.end_date,
      start_time:currentItem.start_time,
      end_time:currentItem.end_time,
      priceType: currentItem.type,
      priceMode: currentItem.priceMode,
      priceModeSwitch: currentItem.priceMode == 0?true:false,
      auction_time_start: currentItem.auction_time_start,
      auction_time_end: currentItem.auction_time_end,
      auction_price_max: currentItem.auction_price_max,
      auction_price_min: currentItem.auction_price_min,
      auction_price_min_protect: currentItem.auction_price_min_protect,
      lpp: currentItem.auction_price_min_protect == 1?true:false,
      dv_deadline: currentItem.dv_deadline,
      price_priority_mode_index: util.pricePriorityMode(currentItem.price_priority_mode)||0,
      vehicle_tags_list: util.arrayDeleteEmpty(String(currentItem.vehicle_tags).split(",")),
      deputy_driver: currentItem.deputy_driver == 1?true:false,
      priceType: currentItem.type,
      carrierName: currentItem.carrierName,
      carrier: currentItem.carrier,
      warehouse: currentItem.warehouse,
      formType: 'edit',
      modalTitle: '修改价格配置',
      modalName: 'viewModal',
      priceTypeList: priceTypeList
    })
    
    if (currentItem.startRegion){
      that.setData({
        startRegion: currentItem.startRegion.split(','),
        endRegion: currentItem.endRegion.split(',')
      })
    }
  },
  //获取车辆属性
  loadVehicleProperty: function () {
    wx.showLoading({
      title: '加载车辆属性...',
      mask: true
    })
    var that = this;
    util.getData("/atapi/vehicle/vehicle/property", {}, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var vehicleLength = res.data.vehicleLength.name;
        //vehicleLength.unshift('请选择');
        var vehicleLengthCode = res.data.vehicleLength.code;
        //vehicleLengthCode.unshift('');

        var vehicleFunction = res.data.vehicleFunction.name;
        //vehicleFunction.unshift('请选择');
        var vehicleFunctionCode = res.data.vehicleFunction.code;
        //vehicleFunctionCode.unshift('');

        var vehicleSource = res.data.vehicleSource.name;
        //vehicleSource.unshift('请选择');
        var vehicleSourceCode = res.data.vehicleSource.code;
        //vehicleSourceCode.unshift('');

        that.setData({
          vehicleLength: vehicleLength,
          vehicleFunction: vehicleFunction,
          vehicleSource: vehicleSource,
          vehicleLengthCode: vehicleLengthCode,
          vehicleFunctionCode: vehicleFunctionCode,
          vehicleSourceCode: vehicleSourceCode
        }); 
      }
      that.loadData();
    });
  },
  vehicleTag: function (e) {
    var tag = e.currentTarget.dataset.tag;
    wx.navigateTo({
      url: '/pages/vehicle/vehicle_tag?tag=' + tag
    })
  },
  //价格配置步骤，返回上一步
  prevTab: function (e) {
    var that = this;
    var num = that.data.num;
    var curNum = that.data.curNum;
    that.setData({
      num: num - 1,
      curNum: curNum - 1
    })
  },
  //价格配置步骤，下一步
  nextTab: function (e) {
    var that = this;
    var num = that.data.num;
    var curNum = that.data.curNum;
    var priceConfig = that.data.priceConfig;
    if (curNum == 0) {
      priceConfig.vehicleLength = that.data.vehicleLengthCode[that.data.vehicleLengthIndex]||'';
      priceConfig.vehicleSource = that.data.vehicleSourceCode[that.data.vehicleSourceIndex] || '';
      priceConfig.vehicleFunction = that.data.vehicleFunctionCode[that.data.vehicleFunctionIndex] || '';
      
      if(that.data.formType == 'add'){
        var errmsg = '';
        if (!priceConfig.vehicleLength){
          errmsg += '车辆规格没有选择,';
        }
        if (!priceConfig.vehicleSource) {
          errmsg += '车辆来源没有选择,';
        }
        if (!priceConfig.vehicleFunction) {
          errmsg += '车辆功能没有选择,';
        }
        if (errmsg != ''){
          wx.showModal({
            title: '温馨提示',
            content: errmsg+'确定不用限定这些车辆属性吗？',
            success(res) {
              if (res.confirm) {
                that.setData({
                  priceConfig: priceConfig,
                  num: num + 1,
                  curNum: curNum + 1
                })
              }
            }
          });
        } else {
          that.setData({
            priceConfig: priceConfig,
            num: num + 1,
            curNum: curNum + 1
          })
        }
      }else{
        that.setData({
          priceConfig: priceConfig,
          num: num + 1,
          curNum: curNum + 1
        })
      }
      
      
    }
    if (curNum == 1) {
      priceConfig.formula = that.data.formula;
      if (that.data.priceType == 'formula') {
          if(priceConfig.formula == ''){
            wx.showToast({
              title: "价格未有配置",
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          }
          if(encodeURIComponent(priceConfig.formula).indexOf('%0A') > -1){
            wx.showToast({
              title: "有换行，请清除",
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          }
          if(String(priceConfig.formula).indexOf('：') > -1){
            wx.showToast({
              title: "冒号请用英文字符",
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          }
          if(String(priceConfig.formula).indexOf('；') > -1){
            wx.showToast({
              title: "分号请用英文字符",
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          }
      }
      if (that.data.priceType == 'region') {
        if (that.data.startRegion.length == 0 || that.data.endRegion.length == 0){
          wx.showToast({
            title: "区域未选择",
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
        priceConfig.formula = that.data.R||'';
        if (priceConfig.formula == '') {
          wx.showToast({
            title: "区域计价未填",
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
        priceConfig.startRegion = that.data.startRegion;
        priceConfig.endRegion = that.data.endRegion;
      }

      that.setData({
        priceConfig: priceConfig,
        num: num + 1,
        curNum: curNum + 1
      })
    }
    if (curNum == 2) {
      priceConfig.priceMode = that.data.priceMode;
      if (that.data.priceMode == 1) {
        if (!that.data.auction_price_max == true) {
          wx.showToast({
            title: "价格上波动错误",
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
        if (!that.data.auction_price_min == true) {
          wx.showToast({
            title: "价格下波动错误",
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
        if (that.data.auction_time_start == that.data.auction_time_end) {
          wx.showToast({
            title: "竞价时间相同",
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
        if (!that.data.dv_deadline && !isNaN(that.data.dv_deadline)) {
          wx.showToast({
            title: "派车时限有误",
            image: '/images/wrong.png',
            duration: 3000
          });
          return false;
        }
        priceConfig.auction_price_max = that.data.auction_price_max;
        priceConfig.auction_price_min = that.data.auction_price_min;
        priceConfig.auction_time_start = that.data.auction_time_start;
        priceConfig.auction_time_end = that.data.auction_time_end;
        priceConfig.auction_price_min_protect = that.data.auction_price_min_protect;
        priceConfig.dv_deadline = that.data.dv_deadline;
        priceConfig.price_priority_mode = util.pricePriorityMode(that.data.price_priority_mode_index);
        priceConfig.vehicle_tags = that.data.vehicle_tags_list.length > 0 ? that.data.vehicle_tags_list.join(','):'';
      } 
      
      that.setData({
        priceConfig: priceConfig,
        num: num + 1,
        curNum: curNum + 1
      })
    }
  },
  //提交价格配置
  savePriceConfig: function () {
    var that = this;

    var priceConfig = that.data.priceConfig;

    priceConfig.start_date = that.data.start_date;
    priceConfig.end_date = that.data.end_date;
    if (priceConfig.start_date == priceConfig.end_date) {
      wx.showToast({
        title: "日期相同",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (moment(priceConfig.start_date) > moment(priceConfig.end_date)) {
      wx.showToast({
        title: "日期开始大于结束",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    priceConfig.start_time = that.data.start_time;
    priceConfig.end_time = that.data.end_time;
    if (priceConfig.start_time == priceConfig.end_time) {
      wx.showToast({
        title: "时间相同",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (moment(priceConfig.start_time) > moment(priceConfig.end_time)) {
      wx.showToast({
        title: "时间开始大于结束",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }

    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    priceConfig.warehouse = (that.data.type == 'warehouse' ? that.data.id : '');
    priceConfig.customer = (that.data.type == 'customer' ? that.data.id : '');
    priceConfig.type = that.data.priceType;
    priceConfig.mode = that.data.mode;
    priceConfig.carrierName = that.data.carrierName||'';
    priceConfig.carrier = that.data.carrier||'';
    priceConfig.deputy_driver = that.data.deputy_driver?1:0;
    priceConfig.CO_ID = app.globalData.CO_ID;
    priceConfig.user_id = app.globalData.user_id;
    if (that.data.formType == 'add'){
      util.postData("/atapi/price/price/savePriceConfig", priceConfig, function (res, error) {
        console.log(res); console.log(error)
        if (res.data.success) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "提交失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
        wx.hideLoading()
      });
    }else{
      priceConfig.id = that.data.pid
      util.putData("/atapi/price/price/editPriceConfig", priceConfig, function (res, error) {
        console.log(res); console.log(error)
        if (res.data.success) {
          wx.showToast({
            title: "编辑成功",
            icon: "success",
            duration: 3000,
            success: function () {
              setTimeout(function () {
                that.hideModal();
                that.loadData();
              }, 3000);
            }
          });
        } else {
          wx.showToast({
            title: "编辑失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
        wx.hideLoading()
      });
    }
    
  },
  //删除价格配置
  deletePriceConfig: function (e) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确定删除吗？',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          util.putData("/atapi/price/price/deletePriceConfig", {
            'id': id,
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              wx.showToast({
                title: "删除成功",
                icon: "success",
                duration: 3000,
                success: function () {
                  setTimeout(function () {
                    that.hideModal();
                    that.loadData();
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: "删除失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }
      }
    })

  },
  //选择车辆属性
  PickerChange(e) {
    console.log(e);
    var type = e.currentTarget.dataset.type;
    if (type == 'length') {
      this.setData({
        vehicleLengthIndex: e.detail.value
      })
    }
    if (type == 'source') {
      this.setData({
        vehicleSourceIndex: e.detail.value
      })
    }
    if (type == 'function') {
      this.setData({
        vehicleFunctionIndex: e.detail.value
      })
    }
    if (type == 'price_priority_mode') {
      this.setData({
        price_priority_mode_index: e.detail.value
      })
    }
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModalB(e) {
    var that = this;
    this.setData({
      bModalName: e.currentTarget.dataset.target
    })
    that.setData({
      vehicleTag: util.vehicleTag
    })
  },
  hideModalB(e) {
    this.setData({
      bModalName: null
    })
  },
  addTag: function (e) {
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var newtag = '';
    var tagArray = that.data.vehicle_tags_list;
    if (!tagArray) {
      tagArray = [];
      tagArray.push(tag);
      newtag = tagArray.join(",");
    } else {
      if (tagArray.indexOf(tag) > -1) {
        wx.showToast({
          title: '同名分类已存在',
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      } else {
        tagArray.push(tag);
        newtag = tagArray.join(",");
      }
    }
    that.setData({
      vehicle_tags_list: tagArray,
      vehicle_tags: tagArray.join(","),
      bModalName: null
    });
  },
  addNewTag: function (e) {
    var that = this;
    var tag = that.data.newtag;
    if (!tag) {
      wx.showToast({
        title: '请输入标签名称',
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var newtag = '';
    var tagArray = that.data.vehicle_tags_list;
    if (!tagArray) {
      tagArray = [];
      tagArray.push(tag);
      newtag = tagArray.join(",");
    } else {
      if (tagArray.indexOf(tag) > -1) {
        wx.showToast({
          title: '同名分类已存在',
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      } else {
        tagArray.push(tag);
        newtag = tagArray.join(",");
      }
    }
    that.setData({
      vehicle_tags_list: tagArray,
      vehicle_tags: tagArray.join(","),
      bModalName: null
    });
  },
  deleteTag: function (e) {
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var vehicle_tags_list = that.data.vehicle_tags_list;
    var newtag = '';
    newtag = util.arrayDeleteItem(vehicle_tags_list, tag);
    if (newtag) {
      wx.showModal({
        title: '温馨提示',
        content: '确认要删除分类【' + tag + '】吗？',
        success(res) {
          if (res.confirm) {
            that.setData({
              vehicle_tags_list: newtag
            });
          }
        }
      })
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: (that.data.mode == 'income' ? '收入' : '支出') + e.currentTarget.dataset.name,
      modalType: e.currentTarget.dataset.type,
      priceType: 'formula',
      start_date: moment().format('YYYY-MM-DD'),
      end_date: moment().format('YYYY-MM-DD'),
      formula: '',
      R: '',
      num: -1,
      curNum: 0,
      formType: 'add'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  //价格配置页面，具体价格设置向导
  inputGuide:function(e){
     var that = this;
     var type = e.currentTarget.dataset.type;
    this.setData({
      modalName: 'viewModal',
      modalTitle: '配置向导',
      modalType: 'configGuide',
      guideType: type,
      miletype:'',
      guideStep:0
    })
  },
  //关闭向导回到价格配置页面
  backToPriceConfig: function (e) {
    var that = this;
    this.setData({
      modalName: 'viewModal',
      modalTitle: (that.data.mode == 'income' ? '收入价格配置' : '支出价格配置'),
      modalType: 'priceConfig',
      guideType: ''
    })
  },
  //公里价格设置的计价类型
  mileGuideType: function (e) {
    var guideStep = this.data.guideStep;
    this.setData({
      guideStep: 1,
      miletype: e.currentTarget.dataset.miletype
    })
  },
  //返回向导第一步
  backGuideStep: function () {
    var that = this;
    that.setData({
      guideStep: 0
    })
  },
  //增加一段向导
  addGuideItem: function () {
    var guideFormulaItem = this.data.guideFormulaItem;
    guideFormulaItem.push({ name: 'gf' + guideFormulaItem.length, symbol1: 0, symbol2: 0, check: false })
    this.setData({
      guideFormulaItem: guideFormulaItem
    })
  },
  moveGuideItem: function () {
    var guideFormulaItem = this.data.guideFormulaItem;
    guideFormulaItem.pop()
    this.setData({
      guideFormulaItem: guideFormulaItem
    })
    this.guideMileFormula();
  },
  //里程价格设置向导结束，保存
  saveMileGuid: function () {
    var that = this;
    var guideType = that.data.guideType;
    if (that.data.miletype == 1){
      if (that.data.guide_M) {
        var item_value = {};
        item_value[guideType] = that.data.guide_M;
        that.setData(item_value);
      }
    } else{
      if (that.data.guideFormula) {
        var item_value = {};
        item_value[guideType] = that.data.guideFormula;
        that.setData(item_value);
      }
    }

    that.formula();
    that.setData({
      guideStep: 0
    })
    that.backToPriceConfig();
  },
  //计算符号切换
  symbolChange(e) {
    console.log(e);
    var id = e.currentTarget.id;
    var index = e.currentTarget.dataset.index;
    var guideFormulaItem = this.data.guideFormulaItem;
    if (id.indexOf("left") > -1) {
      guideFormulaItem[index].symbol1 = e.detail.value
    } else {
      guideFormulaItem[index].symbol2 = e.detail.value
    }
    this.setData({
      guideFormulaItem: guideFormulaItem
    })
  },
  //公里计价输入监听
  bindMileInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;

    var inputtype = e.currentTarget.dataset.inputtype;
    if (inputtype == 'digit' || inputtype == 'number') {
      if (isNaN(value)) {
        value = '';
      }
    }
    item_value[item] = value;
    that.setData(item_value);

    that.guideMileFormula();
  },
  //公里计价向导生成公式
  guideMileFormula: function () {
    var that = this;
    var guideFormulaItem = that.data.guideFormulaItem;
    var guideFormula = '', guideType = that.data.guideType;
    var symbolCode = that.data.symbolCode;
    var sort = 1;
    for (var i = 0; i < guideFormulaItem.length;i++){
      var _guideFormula = '';
      var falseValue = '0';
      if (guideFormulaItem.length > sort && i == sort - 1){
        falseValue = 'F';
      }
      var n = guideFormulaItem[i];
      if (that.data[n.name + '_left_mile'] && that.data[n.name + '_price']){
        _guideFormula = '(' + guideType + String(symbolCode[n.symbol1]) + String(that.data[n.name + '_left_mile']);
        if (that.data[n.name + '_right_mile']) {
          _guideFormula += ' && ';
          _guideFormula += guideType + String(symbolCode[n.symbol2]) + String(that.data[n.name + '_right_mile']);
        }
        if (that.data.miletype == 2) {
          _guideFormula += ')?' + that.data[n.name + '_price'] + ':' + falseValue;
        } else{
          _guideFormula += ')?' + that.data[n.name + '_price'] + '×' + guideType + ':' + falseValue;
        }
      }
      if (i==0) {
        guideFormula = '(' + _guideFormula + ')';
      }else if(guideFormula.indexOf("F")>-1){
        guideFormula = guideFormula.replace("F", '(' + _guideFormula + ')');
      }
      sort++;
    }
    if (guideFormula) {
      that.setData({
        guideFormula: guideFormula
      })
    }
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'path_carrier',
      success: function (res) {
        console.log(res)
        if (res.data) {
          that.setData({
            carrierName: res.data.name,
            carrier:res.data.carrier_coid
          });
        }else{
          that.setData({
            carrierName: '',
            carrier:''
          });
        }
        wx.removeStorage({
          key: 'path_carrier',
          success: function (res) {
          }
        });
      }
    }); 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})